const errorTypes = require('../constants/error-types');
const CustomError = require('../utils/error');
const userService = require('../service/user.service');
const encrypt = require('../utils/secret');

// 校验用户
const validateUser = async (ctx, next) => {
  const { username, password } = ctx.request.body;
  // 1. 校验用户名和密码
  if (!username || !password) {
    const err = new CustomError(errorTypes.USERNAME_OR_PASSWORD_REQUIRED);
    return ctx.app.emit('error', err, ctx);
  }
  // 2.查询是否重复注册
  const result = await userService.findUserByName(username);
  if (result && result.length) {
    return ctx.app.emit('error', new CustomError(errorTypes.USERNAME_EXIST), ctx);
  }
  await next();
};

// 加密密码
const encryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  ctx.request.body.password = encrypt(password);
  await next();
};

const validLogin = async (ctx, next) => {
  const { username, password } = ctx.request.body;
  // 1. 校验用户名和密码
  let err;
  if (!username || !password) {
    err = new CustomError(errorTypes.USERNAME_OR_PASSWORD_REQUIRED);
    return ctx.app.emit('error', err, ctx);
  }
  // 2.查询用户名和密码
  const result = await userService.login({
    username,
    password: encrypt(password),
  });
  // console.log('result:', result);
  if (!result || !result.length) {
    err = new CustomError(errorTypes.USERNAME_OR_PASSWORD_ERROR);
   return ctx.app.emit('error', err, ctx);
  }
  ctx.user = result[0];
  await next();
};

module.exports = {
  validateUser,
  encryptPassword,
  validLogin,
};
